<template xmlns="http://www.w3.org/1999/html">
    <el-form ref="search_from" label-width="100px"
             v-loading="loading" :model="props.model" :rules="props.rules">
        <slot :form_data="props.model"></slot>

        <div class="align-right">
            <el-button :loading="loading" @click="resetForm">重置</el-button>
            <el-button :loading="loading" type="primary" @click="submitForm">提交</el-button>
        </div>
    </el-form>
</template>

<script setup lang="ts">
import {ref, watch} from "vue";
import type {FormInstance} from "element-plus";
import Layers from "@/lang/layers";

/**
 * 修改界面
 */
interface Props {
    // 需要操作的数据对象
    model?: Record<string, any>;
    // 需要操作的数据对象
    rules?: Record<string, any>;
    // 表单提交函数
    submit?: (params: Record<string, any>) => Promise<any>;
    // 成功回调，通常是刷新数据表格
    succeed?: () => void;
}

const props = withDefaults(defineProps<Props>(), {
    model: {}, succeed: Layers.method()
});


// 表单对象实体
const search_from = ref<FormInstance>();
// 是否正在提交
const loading = ref(false);
// 表单默认值
let default_value = {};

/**
 * 提交表单
 */
const submitForm = () => {
    search_from.value.validate((valid, fields) => {
        if (valid) {
            loading.value = true;
            props.submit(props.model).then(ret => {
                // 操作成功弹窗
                Layers.succeed();
                // 执行成功回调
                props.succeed();
            }).finally(() => {
                loading.value = false;
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

/**
 * 重置表单
 */
const resetForm = () => {
    Object.assign(props.model, default_value);
}

// 复制表单数据
watch(() => props.model, val => {
    Object.assign(props.model, val);
    Object.assign(default_value, val);
}, {immediate: true});
</script>
